package com.yuan.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.yuan.reggie.common.BaseContext;
import com.yuan.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yuanxingke
 * @date 2022/7/31 0:37
 */
@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String[] urls = {"/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        String requestURI = request.getRequestURI();

        Boolean flag = matchUrl(urls, requestURI);

        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }

        //员工判断
        Long id = (Long) request.getSession().getAttribute("employee");

        if (id != null) {
            //设置公共数据存储在BaseContext工具类中，使用TreadLocal在同一个线程
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }

        //用户登陆判断
        Long uid = (Long) request.getSession().getAttribute("user");

        if (uid != null) {
            //设置公共数据存储在BaseContext工具类中，使用TreadLocal在同一个线程
            BaseContext.setCurrentId(uid);
            filterChain.doFilter(request, response);
            return;
        }


        log.info("用户未登陆");
        //返回给前端，状态码为1，然后msg为‘NOTLOGIN’
        String login = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().println(login);
    }

    private Boolean matchUrl(String[] urls, String requestURI) {

        AntPathMatcher antPathMatcher = new AntPathMatcher();

        for (String url : urls) {
            boolean b = antPathMatcher.match(url, requestURI);
            if (b) {
                return true;
            }
        }
        return false;
    }

}
